use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::domain::entity::module_entity::ModuleEntity;
use crate::domain::error::{AccountError, AppResult};
use crate::domain::dto::validate::{validate_number_not_zero,validate_string_empty};

/// ModulePageRequest 数据模型分页查询
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModulePageRequest {
    /** 页码 */
    pub page: Option<u64>,
    /** 页大小 */
    pub limit: Option<u64>,
    /** 业务线ID */
    pub biz_id: Option<u64>,
    /** 模型名称 */
    pub name: Option<String>,
}

/// ModulePageResponse 数据源模型响应
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModulePageResponse {
    /** 主键 */
    pub id: u64,
    /** 模型名称 */
    pub name: String,
    /** 模型描述 */
    pub about: Option<String>,
    /** 业务线ID */
    pub biz_id: u64,
    /** 业务线名称 */
    pub biz_name: String,
    /** 所有者 */
    pub owner: Option<String>
}

/// ModuleCreateRequest 模型创建请求
#[derive(Serialize, Deserialize, Clone, Debug, Validate)]
pub struct ModuleCreateRequest {
    #[validate(custom(function = "validate_number_not_zero"))]
    pub biz_id: u64,
    #[validate(custom(function = "validate_string_empty"))]
    pub name: String,
    pub about: Option<String>,
    /** 属性 */
    pub fields: Option<Vec<String>>,
}

/// ModuleFieldVo 模型属性vo
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ModuleFieldVo {
    /** 上级ID */
    pub parent_id: u64,
    /** 属性名称 */
    pub field_name: String,
    /** 属性备注 */
    pub field_about: Option<String>,
    /** 属性类型 */
    pub field_type: i8,
}


impl ModuleCreateRequest {
    pub async fn check(&self) -> AppResult<()> {
        if self.name.is_empty() {
            return Err(AccountError::ModuleNameNotExistError)
        }
        if self.biz_id == 0 {
            return Err(AccountError::ModuleBizNotExistError)
        }
        Ok(())
    }
}

impl Into<ModuleEntity> for ModuleCreateRequest {
    fn into(self) -> ModuleEntity {
        ModuleEntity {
            id: None,
            module_name: self.name,
            module_about: self.about,
            biz_id: self.biz_id,
            owner: None,
        }
    }
}

/// ModuleUpdateRequest 模型更新请求
#[derive(Serialize, Deserialize, Clone, Debug, Validate)]
pub struct ModuleUpdateRequest {
    #[validate(custom(function = "validate_number_not_zero"))]
    pub id: u64,
    #[validate(custom(function = "validate_number_not_zero"))]
    pub biz_id: u64,
    #[validate(custom(function = "validate_string_empty"))]
    pub name: String,
    pub about: Option<String>,
    // 属性
    pub fields: Option<Vec<String>>,
}

impl ModuleUpdateRequest {
    pub async fn check(&self) -> AppResult<()> {
        if self.id == 0 {
            return Err(AccountError::ModuleIdNotExistError)
        }
        if self.name.is_empty() {
            return Err(AccountError::ModuleNameNotExistError)
        }
        if self.biz_id == 0 {
            return Err(AccountError::ModuleBizNotExistError)
        }
        Ok(())
    }
}